#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <memory>
using namespace std;
using namespace Server;


static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " lock_port\n\n";
}

// 将收到的消息转发给所有在线的用户
onlineUsers onlineusers;
void routeMessage(const int &sockfd, const string &clientip, const uint16_t &clientport, const string &message)
{
    if (message == "online")
        onlineusers.addUser(clientip, clientport);
    if (message == "offline")
        onlineusers.delUser(clientip, clientport);
    // 判断用户是否在线
    if (onlineusers.ifUserOnline(clientip, clientport))
    {
        // 消息的路由
        onlineusers.broadCastMessage(sockfd, clientip, clientport, message);
    }
    else // 不在线，向其发送消息
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));

        client.sin_family = AF_INET;
        client.sin_port = htons(clientport);
        client.sin_addr.s_addr = inet_addr(clientip.c_str());

        string response = "你还没有上线，请先上线 : 输入 online 上线";
        sendto(sockfd, response.c_str(), response.size(), 0, (sockaddr *)&client, sizeof(client));
    }
}

// ./UdpServer ip prot
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<udpserver> usvr(new udpserver(routeMessage, port));
    usvr->initServer();
    usvr->start();
    return 0;
}
